<template>
<!--查询-->
<div style="margin-bottom: 15px;">
  角色名:<el-input v-model="form.roleName" placeholder="请输入角色名" style="width: 240px;"></el-input>
  <el-button type="primary" @click="getRole">查询</el-button>
</div>

  <!--角色列表-->
<el-table :data="roleData" border style="width: 100%">
    <el-table-column prop="roleId" label="编号" align="center" />
    <el-table-column prop="roleName" label="角色名称" align="center" >
      <template v-slot="scope">
        <el-link :underline="true" @click="checkRole(scope.row.roleId)">{{ scope.row.roleName }}</el-link>
      </template>
    </el-table-column>
    <el-table-column prop="createdBy" label="创建人" align="center" />
    <el-table-column prop="createdDate" label="创建日期" align="center" width="155px" />
    <el-table-column prop="updatedBy" label="修改人" align="center" />
    <el-table-column prop="updatedDate" label="修改日期" align="center" width="155px" />
    <el-table-column label="操作" align="center" width="260px" >
      <template v-slot="scope">
        <el-button type="primary" @click="UpdateUserInfo(scope.row.roleId)">修改</el-button>
        <el-button type="danger" @click="delUserInfo(scope.row.roleId)">删除</el-button>
        <el-button type="warning" @click="AssignPersonnel(scope.row.roleId)">分配人员</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="form.dialogTableVisible" width="900" style="height: 300px;">
    <h2>请设置<span style="color:red;font-weight: bold;">【{{ form.roleName }}】</span>角色的员工:</h2>

    <div class="common-layout" style="margin-top: 25px;">
    <el-container>
      <el-aside width="400px">
        <el-tree ref="treeRef" style="width: 390px" :data="data" show-checkbox default-expand-all node-key="id" highlight-current :props="defaultProps" @check-change="getCheckedKeys" :default-checked-keys="departmentData"/>
      </el-aside>

      <el-main>
       <el-tree ref="treeRef1" style="width: 390px" :data="staffData" show-checkbox default-expand-all node-key="id" highlight-current :props="defaultProps" @check-change="getCheckedKeys1" :default-checked-keys="userInfoBackData" />
      </el-main>
    </el-container>

    <div style="float: right;">
      <el-button type="primary" @click="saveData">确定保存</el-button>
    </div>
  </div>
  </el-dialog>

  <el-dialog v-model="form.dialogTableVisible1" width="900" style="height: 300px;" center>
    <h2>属于角色<span>【{{ form.roleName1 }}】</span>的员工如下:</h2>
    <div style="float: right;">
        <el-link @click="form.dialogTableVisible1=false"><span style="font-weight: bold;">*关闭*</span></el-link>
      </div>
    <div style="margin-top: 30px;">
      <div style="margin-top: 20px;">
        <span v-for="item in userInfoDatas" :key="item.userId" style="font-weight: bold;font-size: larger;">
        &nbsp;&nbsp;
        {{item.userName }}&nbsp;
        <el-link @click="delUserInfoRole(item.userId,item.roleId)">x</el-link>
        &nbsp;&nbsp;
        <el-link  @click="openAdd(item.roleId)"><span style="font-weight: bold;font-size: larger;">+</span></el-link>
      </span>    
      </div>
    </div>
  </el-dialog>

    <!--分页-->
<table>
  <thead></thead>
  <tbody>
    <tr>
      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[3, 5, 7, 9]" :background="true" layout="total,slot, sizes" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <span>
            ，每页{{ form.pageSize }}条，当前第:{{ form.pageIndex }}/{{ form.pageCount }}页
          </span>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, prev, pager, next" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(1)" :disabled="form.pageIndex==1">首页</el-button>
        </el-pagination>
      </td>

      <td>
        <el-pagination v-model:current-page="form.pageIndex" v-model:page-size="form.pageSize" :page-sizes="[100, 200, 300, 400]" :background="true" layout="slot, jumper" :total="form.totalCount" prev-text="上一页" next-text="下一页" @size-change="handleSizeChange" @current-change="handleCurrentChange">
          <el-button type="primary" class="btn-prev" @click="handleCurrentChange(form.pageCount)" :disabled="form.pageIndex==form.pageCount">尾页</el-button>
        </el-pagination>
      </td>
    </tr>
  </tbody>
</table>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue'
import axios from 'axios';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ElTree } from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'

import {useRoute,useRouter} from 'vue-router'

const route = useRoute();
const router = useRouter();

const dialogTableVisible = ref(false)

interface Tree {
  id: number
  label: string
  children?: Tree[]
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeRef1 = ref<InstanceType<typeof ElTree>>()

const defaultProps = {
  children: 'children',
  value:'value',
  label: 'label',
}

//部门静态数据
const data = ref([
{
  id: 0,
    label: '请选择部门',
    children: [
      {
        id: 1,
        label: 'IT信息部',
      },
      {
        id: 2,
        label: '人力资源部',
      },
      {
        id: 3,
        label: '财务部',
      },
      {
        id: 4,
        label: '销售部',
      },
      {
        id: 5,
        label: '行政部',
      },
    ]
},
])

onMounted(() => {
  getRole()
})

const form: any = reactive({
  dialogTableVisible: false,
  dialogTableVisible1:false,
  roleName: '',
  roleName1: '',
  roleId: 0,
  userName: '',
  pageIndex: 1,
  pageSize: 5,
  pageCount:0,
  totalCount:0,
})

//分页
const handleSizeChange = (val: number) => {
  form.pageSize = val;
  getRole()
}
const handleCurrentChange = (val: number) => {
  form.pageIndex = val;
  getRole()
}

let strIds: string = "";
let userIds: any = [];
//员工
const staffData = ref([
  {
    id: 0,
    label: '请选择员工',
    children: [
  ]
}
])

//员工树形
const getCheckedKeys = () => {
  //console.log(treeRef.value!.getCheckedKeys(false))
  strIds=(treeRef.value!.getCheckedKeys(false)).join(',')
  //console.log(strIds);
  let ids = {
    ids:strIds
  }
  axios.post('/api/UserManagemement/SearchInfo', ids).then(res=>{
    console.log(res);
    staffData.value[0].children = res.data.data;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//用户树形
const getCheckedKeys1 = () => {
  //console.log(treeRef1.value!.getCheckedKeys(false))
  userIds.value = treeRef1.value!.getCheckedKeys(false)
  //console.log(userIds.value);
}

//角色列表
const roleData:any=ref([])
const getRole = () => {
  let role = {
    pageIndex: form.pageIndex,
    pageSize: form.pageSize,
    roleName:form.roleName
  }
  axios.post('/api/RoleManagement/GetAll',role).then(res=>{
    //console.log(res);
    roleData.value = res.data.data.list;
    form.pageCount = res.data.data.pageCount;
    form.totalCount = res.data.data.totalCount;
  }).catch(err=>{
    console.log(err);
    
  })    
}

//修改
const UpdateUserInfo = (roleId:number) => {
  router.push({
    "name": 'UpdateRole',
    query: {
      roleId:roleId
    }
  })
}

//删除
const delUserInfo = (roleId: number) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      let getRoleId = {
        roleId:roleId
      }
      axios.post('/api/RoleManagement/Remove',getRoleId).then(res => {
        console.log(res);
        if (res.data.code == 0) {
          ElMessage.success("删除成功!")
          //刷新页面
          getRole()
        } else {
          ElMessage.error("刷新失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//存储反填的部门数组id
const departmentData=ref([])
//存储反填的用户数组id
const userInfoBackData = ref([])

//点击分配人员
const AssignPersonnel = (roleId: any) => {
  //弹出层
  form.dialogTableVisible = true;
  //反填角色名称
  let getRoleId = {
    roleId:roleId
  }
  axios.post('/api/RoleManagement/SearchBackRole',getRoleId).then(res=>{
      console.log(res);
      form.roleName = res.data.data.roleName;
    form.roleId = res.data.data.roleId;
    BackDepartment(roleId)
    }).catch(err=>{
      console.log(err);      
    })   
    
}

//反填部门信息
const BackDepartment = (roleId:number) => {
  let getDepartment = {
    roleId: roleId
  }
  axios.post('/api/UserInfoRoleManagement/SearchDepartmentByRoleId', getDepartment).then(res => {
    //console.log(res.data.data);
    departmentData.value = res.data.data.map((x: any) => x.id)
    //console.log( departmentData.value);
    BackUserInfo(roleId)
  }).catch(err => {
    console.log(err);
  })
}
//反填用户信息
const BackUserInfo = (roleId:number) => {
  //反填用户信息
  let getUserInfo = {
    roleId:roleId
  }
  axios.post('/api/UserInfoRoleManagement/SearchUserInfoByRoleId',getUserInfo ).then(res=>{
      console.log(res.data.data);
      userInfoBackData.value = res.data.data.map((x: any) => x.id)
      //console.log( userInfoBackData.value);
    }).catch(err=>{
      console.log(err);      
    })
}

//保存
const saveData = () => {
  //console.log(userIds.value);
  let add: any = {
    ids:userIds.value,
    roleId: form.roleId
  }
  axios.post('/api/UserInfoRoleManagement/Creare', add).then(res => {
    console.log(res);
    console.log(userIds);
    
    if (res.data.code == 0) {
      ElMessage.success("保存成功")
      //关闭弹出层
      form.dialogTableVisible = false;
      checkRole(form.roleId)
    } else {
      ElMessage.error("保存失败!");
      return
    }
  }).catch(err => {
    console.log(err);

  })
}

//查看角色--员工
//存储用户姓名数组
const userInfoDatas:any=ref([])
const checkRole = (roleId:number) => {
  form.dialogTableVisible1 = true;
  //显示角色名称 + 员工
  let getRoleId = {
    roleId:roleId
  }
  axios.post('/api/RoleManagement/GetRoleModel', getRoleId).then(res=>{
      console.log(res);
      userInfoDatas.value = res.data.data;
      form.roleName1 = res.data.data[0].roleName;        
    }).catch(err=>{
      console.log(err);      
    })    
}

//删除用户角色
const delUserInfoRole = (userId: number, roleId: number) => {
  let delUserInfoRole = {
    userId: userId,
    roleId:roleId
  }
  ElMessageBox.confirm(
    '确定要删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      axios.post('/api/UserInfoRoleManagement/Remove', delUserInfoRole).then(res => {
        console.log(res);
        if (res.data.code == 0) {
          ElMessage.success("用户角色信息删除成功!");
          //刷新页面
          getRole()
          //打开弹出层
          form.dialogTableVisible1 = true;
        } else {
          ElMessage.error("用户角色信息删除失败!")
          return
        }
      }).catch(err => {
        console.log(err);

      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//点击+号后
const openAdd = (roleId: number) => {
  form.dialogTableVisible1 = false,
  form.dialogTableVisible = true
  AssignPersonnel(roleId)
}

</script>

<style scoped>

</style>